﻿using System;
using System.Collections.Generic;
using System.Management;
using System.Diagnostics;

namespace BizTalkOneService
{
    public class BizTalkHosts
    {
        EventLog appLog = new EventLog();
        private int HostInstancesRunning = 0;
        private int HostInstancesStopped = 0;
        private int HostInstancesStartPending = 0;
        private int HostInstancesStopPending = 0;
        private int HostInstancesTotal = 0;

        public BizTalkHosts()
        {
            try
            {
                EnumerationOptions enumOptions = new EnumerationOptions();
                enumOptions.ReturnImmediately = false;
                ManagementObjectSearcher searchObject = new ManagementObjectSearcher("root\\MicrosoftBizTalkServer", "Select * from MSBTS_HostInstance where HostType=1", enumOptions);
                foreach (ManagementObject inst in searchObject.Get())
                {
                    if (inst["ServiceState"].ToString() == "4")
                        this.HostInstancesRunning++;
                    if (inst["ServiceState"].ToString() == "2")
                        this.HostInstancesStartPending++;
                    if (inst["ServiceState"].ToString() == "3")
                        this.HostInstancesStopPending++;
                    if (inst["ServiceState"].ToString() == "1")
                        this.HostInstancesStopped++;
                    this.HostInstancesTotal++;
                }

            }
            catch (Exception ex)
            {
                appLog.Source = Settings.EventLogSource;
                EventLogEntryType eventType = EventLogEntryType.Error;
                appLog.WriteEntry("Error retrieving host status: " + ex.Message.ToString() + "\n" + ex.StackTrace, eventType);  
            }

        }

        public List<Counter> GetAllHosts()
        {
            List<Counter> counterList = new List<Counter>();
            counterList.Add(new Counter { CounterCategory = "Host", CounterName = String.Format("Running   ({0})", this.HostInstancesTotal), CounterValue = this.HostInstancesRunning });
            counterList.Add(new Counter { CounterCategory = "Host", CounterName = "Start-Pending", CounterValue = this.HostInstancesStartPending  });
            counterList.Add(new Counter { CounterCategory = "Host", CounterName = "Stop-Pending", CounterValue = this.HostInstancesStopPending });
            counterList.Add(new Counter { CounterCategory = "Host", CounterName = String.Format("Stopped   ({0})", this.HostInstancesTotal), CounterValue = this.HostInstancesStopped });
            return counterList;
        }

    }
}

